package com.example.demo.controller;

import com.example.demo.service.FileService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping("/files")
public class FileController {

    private final FileService fileService;

    @Autowired
    public FileController(FileService fileService) {
        this.fileService = fileService;
    }

    // 上传文件
    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            String fileName = fileService.uploadFile(file);
            return ResponseEntity.ok("File uploaded successfully: " + fileName);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("Failed to upload file: " + e.getMessage());
        }
    }

    // 下载文件
    @GetMapping("/download/{fileName}")
    public ResponseEntity<byte[]> downloadFile(@PathVariable String fileName) {
        try {
            // 生成一个字节数组来存储文件内容
            ByteArrayOutputStream outputStream = new java.io.ByteArrayOutputStream();
            fileService.downloadFile(fileName, outputStream);
            byte[] fileContent = outputStream.toByteArray();

            // URL encode the filename to ensure Unicode compatibility
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8)
                    .replace("+", "%20");

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + encodedFileName)
                    .body(fileContent);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(null);
        }
    }

    @GetMapping("/presigned-download/{fileName}")
    public String getPresignedUrl(@PathVariable String fileName) {
        try {
            // 生成 1 小时有效期的预签名 URL
            return fileService.getPresignedDownloadUrl(fileName, 1);
        } catch (Exception e) {
            e.printStackTrace();
            return "Error generating presigned URL";
        }
    }

    @GetMapping("/downloadStream/{filename}")
    public void downloadStreamFile(@PathVariable String filename, boolean isPreview, HttpServletResponse response) {
        try {
            fileService.downloadStream(filename, isPreview, response);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/hello")
    public String hello() throws InterruptedException, ExecutionException {
        CompletableFuture<String> completableFuture = fileService.hello();
        return completableFuture.get();
    }
}
